package cn.qinggu.cloud.common.character;

/**
 * 字符串转换工具类
 *
 * @author: sky
 * @date: 2017/10/13 13:51
 */
public class CharacterConvertUtil {

    public static final char UNDERLINE = '_';

    /**
     * 驼峰格式字符串转换为下划线格式字符串
     * 会首先去除掉字符串中原有的下划线(否则不可逆)
     * 如果包含大写字母，则将大写字母前面添加下划线（首字母为大写除外）
     * 最终将整个字符串转换为小写的下划线格式
     *
     * @param param
     * @return
     */
    public static String camelToUnderline(String param) {
        String result = "";
        if (isNotEmpty(param)) {
            param = param.replace(UNDERLINE + "", "");//首先将字符串中原有的下划线去除掉
            int length = param.length();
            StringBuilder sb = new StringBuilder(length);
            for (int i = 0; i < length; i++) {
                char c = param.charAt(i);
                if (Character.isUpperCase(c) && i > 0) {//第一个字符如果是大写则无需在前面添加下划线
                    sb.append(UNDERLINE);//如果遇到大写字母则先添加一个下划线
                }
                sb.append(c);
            }
            result = sb.toString().toLowerCase();
        }
        return result;
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串
     * 首先将整个字符串转换为小写(否则不可逆)
     * 如果包含下划线，则将下划线去掉，并将下划线的下一位字符转换为大写
     * 如果下划线处于开头或结尾位置，则直接将下划线去掉，不作下一位字符串大写转换处理
     *
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        String result = "";
        if (isNotEmpty(param)) {
            param = param.toLowerCase();//先将字符串统一转换为小写
            if (param.contains(UNDERLINE + "")) {//如果包涵下划线
                int length = param.length();
                StringBuilder sb = new StringBuilder(length);
                for (int i = 0; i < length; i++) {
                    char c = param.charAt(i);
                    if (c == UNDERLINE) {//
                        if (i > 0 && ++i < length) {
                            //获得下划线的下一位并转换为大写
                            sb.append(Character.toUpperCase(param.charAt(i)));
                        }
                    } else {
                        sb.append(c);
                    }
                }
                result = sb.toString();
            } else {
                result = param;
            }
        }
        return result;
    }

    public static boolean isNotEmpty(String param) {
        return (param != null || "".equals(param.trim()));
    }

    public static void main(String[] args) {
        String str = "loginName";
        System.out.println(str + "-->" + camelToUnderline(str));
        str = "UserDetail";
        System.out.println(str + "-->" + camelToUnderline(str));


        str = "login_name";
        System.out.println(str + "-->" + underlineToCamel(str));
        str = "_login_name";
        System.out.println(str + "-->" + underlineToCamel(str));
        str = "login_name_";
        System.out.println(str + "-->" + underlineToCamel(str));
        str = "login_otherDetail";
        System.out.println(str + "-->" + underlineToCamel(str));
    }


}
